package com.server.llh.llhserverwork.activity.my;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lelaohui.net.BaseLeLaohuiAcitivity;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.NetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.adapter.SpinnerAdapter;
import com.server.llh.llhserverwork.bean.AddressAll;
import com.server.llh.llhserverwork.bean.AddressManagerBean;
import com.server.llh.llhserverwork.bean.AllProvinceBean;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.ShiContentData;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 新增地址
 */
public class LlhAddAddressActivity extends BaseLeLaohuiAcitivity {
    public static final String TAG = "AddAddress";
    @BindView(R.id.ll_save_address)
    Button btn;
    @BindView(R.id.left_btn)
    ImageButton leftBtn;
    @BindView(R.id.titlebar_text)
    TextView titlebarText;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.ll_choose_lianxiren)
    LinearLayout llChooseLianxiren;
    @BindView(R.id.diqu)
    TextView diqu;
    @BindView(R.id.et_diqu)
    TextView etDiqu;
    @BindView(R.id.rl_choose_diqu)
    RelativeLayout rlChooseDiqu;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.rl_parent)
    RelativeLayout rlParent;
    @BindView(R.id.shengTxt)
    TextView shengTxt;
    @BindView(R.id.shengSpinner)
    Spinner shengSpinner;
    @BindView(R.id.shiTxt)
    TextView shiTxt;
    @BindView(R.id.shiSpinner)
    Spinner shiSpinner;
    @BindView(R.id.xianTxt)
    TextView xianTxt;
    @BindView(R.id.xianSpinner)
    Spinner xianSpinner;
    @BindView(R.id.image_Select)
    ImageView imageSelect;
    List<AllProvinceBean.DataBean> dataBeanList = new ArrayList<>();
    AllProvinceBean dataBean = new AllProvinceBean();
    ShiContentData shiContentData = new ShiContentData();
    List<ShiContentData.DataBean> sBeanList = new ArrayList<ShiContentData.DataBean>();
    long optIdSheng, optIdShi, optIdXian;
    private String intentType, mToken, mUserId, addressId, shengName, shiName, xianName, addressAll, code;
    AddressManagerBean.DataBean addressManagerData = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        mToken = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR, getApplicationContext());
        if (getIntent() != null) {
            mUserId=getIntent().getStringExtra("userId");
            code = getIntent().getStringExtra("code");
            if (getIntent().getStringExtra("intentType") != null) {
                intentType = getIntent().getStringExtra("intentType");
            }
            if ((AddressManagerBean.DataBean) getIntent().getSerializableExtra("addressManager") != null) {
                addressManagerData = (AddressManagerBean.DataBean) getIntent().getSerializableExtra("addressManager");
                etName.setText(addressManagerData.getContactName());
                etPhone.setText(addressManagerData.getContactPhone());
                etAddress.setText(addressManagerData.getAddressDetail());
                addressId = String.valueOf(addressManagerData.getAddressId());
            }
        } else {
            code = "0";
        }

        titlebarText.setText("新增地址");
        reqAllProvinceData();
        shengSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AddressAll addressAll = addressAllList.get(position);
                optIdSheng = addressAll.getOptId();
                shengName = addressAll.getOptName();
                reqAllCityData(optIdSheng);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        shiSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AddressAll addressAll = shiAllList.get(position);
                optIdShi = addressAll.getOptId();
                shiName = addressAll.getOptName();
                reqAllDistrictData(optIdShi);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        xianSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AddressAll addressAll = xianAllList.get(position);
                optIdXian = addressAll.getOptId();
                xianName = addressAll.getOptName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void reqMyAddressData(String code, String addressAll, String addressDetail, String contactPhone, String contactName) {
        LRequest lRequest = new LRequest();
        if ("2".equals(code)) {
            lRequest.addParam("addressId", addressId);
        }
        lRequest.addParam("code", code);
        lRequest.addParam("userId", mUserId);
        lRequest.addParam("addressType", 1);
        lRequest.addParam("addressAll", addressAll);
        lRequest.addParam("addressProvinceId", optIdSheng);
        lRequest.addParam("addressProvinceName", shengName);
        lRequest.addParam("addressCityId", optIdShi);
        lRequest.addParam("addressCityName", shiName);
        lRequest.addParam("addressDistrictId", optIdXian);
        lRequest.addParam("addressDistrictName", xianName);
        lRequest.addParam("addressDetail", addressDetail);
        lRequest.addParam("contactPhone", contactPhone);
        lRequest.addParam("contactName", contactName);
        lRequest.addParam("token", mToken);
        lRequest.setUri(ServerPort.GET_MY_ADDRESS);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimErrorToast(getApplicationContext(), "请求失败！");
            }

            @Override
            public void onNext(String responseBean, String code) {
//                com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "添加成功！");
//                onBackPressed();
                if (Constants.RESPON_SUCC_CODE.equals(code)) {
                    com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "添加成功！");
                    onBackPressed();
                } else {
                    com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "添加失败，请确认信息！");
                }
            }
        });
    }

    List<AddressAll> addressAllList = new ArrayList<AddressAll>();
    List<AddressAll> shiAllList = new ArrayList<AddressAll>();
    List<AddressAll> xianAllList = new ArrayList<AddressAll>();

    private void reqAllProvinceData() {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", mToken);
        lRequest.setUri(ServerPort.GET_ALL_PROVINCE);
        lRequest.setUriType(UrlsTools.ADDRESS_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimErrorToast(getApplicationContext(), "请求超时！");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (Constants.RESPON_SUCC_CODE.equals(code) && responseBean != null) {
                    dataBean = new Gson().fromJson(responseBean.toString(), AllProvinceBean.class);
                    dataBeanList = dataBean.getData();
                    if (dataBeanList != null) {
                        for (int i = 0; i < dataBeanList.size(); i++) {
                            AddressAll addressAll = new AddressAll();
                            addressAll.setId(dataBeanList.get(i).getId());
                            addressAll.setOptId(dataBeanList.get(i).getProviceId());
                            addressAll.setOptName(dataBeanList.get(i).getProviceName());
                            addressAllList.add(addressAll);
                        }
                        SpinnerAdapter spinnerAdapter = new SpinnerAdapter(getApplicationContext(), addressAllList);
                        shengSpinner.setAdapter(spinnerAdapter);
                    }
                } else {
                    com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "查询失败，请稍后再试！");
                }
            }
        });
    }

    private void reqAllCityData(long provinceId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("provinceId", provinceId);
        lRequest.addParam("token", mToken);
        lRequest.setUri(ServerPort.GET_ALL_CITY);
        lRequest.setUriType(UrlsTools.ADDRESS_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimErrorToast(getApplicationContext(), "请求超时！");

            }

            @Override
            public void onNext(String responseBean, String code) {
                if (Constants.RESPON_SUCC_CODE.equals(code) && responseBean != null) {
                    sBeanList.clear();
                    shiContentData = new Gson().fromJson(responseBean.toString(), ShiContentData.class);
                    sBeanList = shiContentData.getData();
                    if (sBeanList != null) {
                        for (int i = 0; i < sBeanList.size(); i++) {
                            AddressAll addressAll = new AddressAll();
                            addressAll.setId(sBeanList.get(i).getId());
                            addressAll.setOptId(sBeanList.get(i).getCityId());
                            addressAll.setOptName(sBeanList.get(i).getCityName());
                            shiAllList.add(addressAll);
                        }
                        SpinnerAdapter spinnerAdapter = new SpinnerAdapter(getApplicationContext(), shiAllList);
                        shiSpinner.setAdapter(spinnerAdapter);
                    }
                } else {
                    com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "查询失败，请稍后再试！");
                }
            }
        });
    }

    private void reqAllDistrictData(long cityId) {
        LRequest lRequest = new LRequest();
        BigDecimal bd = new BigDecimal(cityId);
        Log.d(TAG, "bd.toPlainString()==" + bd.toPlainString() + "cityId==" + cityId);
        lRequest.addParam("cityId", bd.toPlainString());
        lRequest.addParam("token", mToken);
        lRequest.setUri(ServerPort.GET_ALL_DISTRICT);
        lRequest.setUriType(UrlsTools.ADDRESS_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimErrorToast(getApplicationContext(), "请求超时！");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (Constants.RESPON_SUCC_CODE.equals(code) && responseBean != null) {
                    xianAllList.clear();
                    try {
                        JSONObject jsonObject = new JSONObject(responseBean);
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject tempJson = jsonArray.getJSONObject(i);
                            AddressAll addressAll = new AddressAll();
                            addressAll.setId(tempJson.getInt("id"));
                            addressAll.setOptId(tempJson.getInt("countyId"));
                            addressAll.setOptName(tempJson.getString("countyName"));
                            xianAllList.add(addressAll);
                        }
                        SpinnerAdapter spinnerAdapter = new SpinnerAdapter(getApplicationContext(), xianAllList);
                        xianSpinner.setAdapter(spinnerAdapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "获取失败，请稍后再试！");
                }
            }
        });
    }

    @Override
    public void showProgress() {
        try {
            showProgress(LlhAddAddressActivity.this);
        } catch (Exception e) {
        }
    }

    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception e) {
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return NetRequestManager.getInstance();
    }



    @OnClick({R.id.left_btn, R.id.ll_choose_lianxiren, R.id.et_diqu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_btn:
                onBackPressed();
                break;
            case R.id.ll_choose_lianxiren:
                startActivityForResult(new Intent(
                        Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);
                break;
            case R.id.et_diqu:

                break;
        }
    }

    @OnClick(R.id.ll_save_address)
    public void onViewClicked() {
        String etAddressStr = etAddress.getText().toString();
        String contactPhone = etPhone.getText().toString();
        String contactName = etName.getText().toString();
        if (TextUtils.isEmpty(etAddressStr)) {
            com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "详细地址不能为空！");
            return;
        }
        if (TextUtils.isEmpty(contactPhone)) {
            com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "电话号码不能为空！");
            return;
        }
        if (TextUtils.isEmpty(contactName)) {
            com.family.llh.lelaohuitoastview.dialog.toast.T.showAnimToast(getApplicationContext(), "用户名不能为空！");
            return;
        }
        addressAll = shengName + shiName + xianName + etAddressStr;
        Log.d(TAG,"addressAll=="+addressAll);
        reqMyAddressData(code, addressAll, etAddressStr, contactPhone, contactName);
    }

    String username, usernumber;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            ContentResolver reContentResolverol = getContentResolver();
            Uri contactData = data.getData();
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                    null, null);
            while (phone.moveToNext()) {
                usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                if (!TextUtils.isEmpty(usernumber)) {
                    etName.setText(username);
                    etPhone.setText(usernumber);
                }
            }
        }

    }

    @Override
    protected int getlayout() {
        return R.layout.llh_add_address;
    }

}
